/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.user;

import java.awt.Dimension;
import java.awt.Image;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.util.MissingResourceException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.servengine.image.ThumbnailUtils;

import javax.mail.internet.InternetAddress;

import org.apache.commons.beanutils.PropertyUtils;

/**
 * This struts action class groups user actions.
 * @see UserActionForm
 * @see User
 * @see UserAdminActions
 */
public class UserActions extends com.servengine.struts.ClientAction
{
	private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(UserActions.class.getName());

//	MailRelayLocal mailRelay;
	public void initAction(javax.naming.Context context)
	{
		/*try
		{
			mailRelay = (MailRelayLocal) initialcontext.lookup("MailRelay/local");
		} catch (Exception e)
		{
			log.error(e.getMessage(), e);
			throw new IllegalStateException(e.getMessage());
		}*/
		log.info(getClass().getName()+" initialized");
	}


	/**
	 * @deprecated Please use unspecified() method
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	public ActionForward get(ActionMapping mapping, ActionForm form, HttpServletRequest request,
		HttpServletResponse response) throws IOException, ServletException
	{
		return unspecified(mapping, form, request, response);
	}

	public ActionForward store(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
		  UserActionForm userForm = (UserActionForm)form;
		  if (userForm.getNewpassword() != null && userForm.getNewpassword().length() > 0 && userSession.getPortal().getBooleanProperty("user.checkOldPasswordOnPasswordChange") && !userSession.getUser().checkEncodedPassword(userForm.getPassword()))
				throw new IllegalArgumentException("error.invalidUseridOrPassword");
		  for (ExtraUserdataField field: userSession.getUser().getPortal().getExtraUserdataFields())
		    if (field.isRequired() && (userForm.getExtraUserdataMap().get(field.getName())==null || userForm.getExtraUserdataMap().get(field.getName()).equals("")))
		      throw new IllegalArgumentException("error.missingRequiredField");
			User user = userSession.getUser();//usermanager.getUser(userSession.getPortalid(),userForm.getPkey());
			if (!user.getUserid().equals(userForm.getUserid()) || !user.getId().equals(userForm.getId()))
				throw new IllegalArgumentException();
			String password=user.getPassword();//Se va a borrar con el siguiente copyProperties.
			PropertyUtils.copyProperties(user,userForm);
		  if (userForm.getNewpassword()!=null && userForm.getNewpassword().length()>0)
		  {
		    if (!userForm.getNewpassword().equals(userForm.getNewpassword2()))
		      throw new IllegalArgumentException("error.passwordsMustBeTheSame");
		    user.encodePassword(userForm.getNewpassword());
		  } else
				user.setPassword(password);
		  if (userForm.getPictureFile()!=null && userForm.getPictureFile().getFileSize()>0)
			{
				Image picture = ThumbnailUtils.JPEGtoImage(userForm.getPictureFile().getInputStream());
				if (userForm.pictureFile.getFileSize()>1024*1024 || picture.getWidth(null)>320 || picture.getHeight(null)>240) //TODO poner esto como parámetro de aplicación
				{
					BufferedImage bufferedImage = ThumbnailUtils.getScaledimage(picture,new Dimension(320,240));
					ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
				  ThumbnailUtils.writeJPG(bufferedImage,byteOutputStream,(float)0.5);
					user.setPicture(byteOutputStream.toByteArray());
					//ThumbnailUtils.writeJPG(bufferedImage,new java.io.File(getServicedir(user.getPortalid(),"user",true),user.getPkey()+".jpg"),(float)0.5);
				} else
				  //new com.servengine.util.File(getServicedir(user.getPortalid(),"user",true),user.getPkey()+".jpg").store(userForm.getPicture().getInputStream());
					user.setPicture(userForm.getPictureFile().getFileData());
				//user.setHasPicture(true);
			} /*else
				user.setHasPicture(new java.io.File(getServicedir(user.getPortalid(),"user",true),user.getPkey()+".jpg").exists());*/
			usermanager.persist(user, userForm.getExtraUserdataMap());
			userForm.setNewpassword(null);
			userForm.setNewpassword2(null);
			userSession.refresh(user);
		  logManager.log(userSession.getPortalid(),userSession.getUser().getId(),"user","UserActions","store",user.getUserid(),request.getRemoteAddr());
		  return unspecified(mapping,form,request,response);
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
		  saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
		HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
		  UserSessionSBean userSession = getUserSession(request);
		  UserActionForm user = (UserActionForm)form;
			org.apache.commons.beanutils.PropertyUtils.copyProperties(user,userSession.getUser());
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
		  saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}
	public ActionForward removePicture(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
	  UserSessionSBean userSession = getUserSession(request);
		try
		{
		  userSession.getUser().setPicture(null);
			usermanager.removeUserPicture(userSession.getUser());
			//new java.io.File(getServicedir(userSession.getPortalid(),"user",true),userSession.getUser().getPkey()+".jpg").delete();
			//userSession.getUser().setHasPicture(false);
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
		  saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return unspecified(mapping,form,request,response);
	}
	public ActionForward signdown(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			User userDTO = userSession.getUser();
			for (Role role: userDTO.getRoles())
				if (role.getName().equals(userSession.getPortal().getAdminRoleName()))
					throw new IllegalArgumentException("error.cantSelfSigndownAsYouAreAdminUser");
			if (!userSession.getPortal().isUserSelfSignup())
				throw new IllegalArgumentException("portal.userSelfSignupDisabled");
		  UserActionForm user = (UserActionForm)form;
			if (!userDTO.checkEncodedPassword(user.getPassword()))
				throw new IllegalArgumentException("error.invalidUseridOrPassword");
		  request.getSession().invalidate();
		  removeRememberedSession(userDTO.getPortal().getId(),response);
			usermanager.removeUser(userDTO.getPortalid(),userDTO.getUserid());
			
		  String html = getServletContextUtils().getResourceAsString(userSession.getUser(),request,response,"/user/signdownConfirmationMail.jsp");
		  getMailRelay().send(portalmanager.getEmail(userSession.getPortalid()).getAddress(), userDTO.getEmail(), "Signdown confirmation", null, html);
			
		  logManager.log(user.getPortalid(),user.getId(),"user","UserActions","signdown",userSession.getUserid(),request.getRemoteAddr());
			return mapping.findForward("signdown");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	protected void removeRememberedSession(String portalid, HttpServletResponse response) throws IOException,ServletException
	{
		javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("servengineautologin#"+portalid,"");
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	public ActionForward follow(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			userSession.refresh(usermanager.follow(userSession.getPortalid(),userSession.getUser().getId(),((UserActionForm)form).getUserid()));
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("followSuccess");
	}
	public ActionForward unFollow(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
		  UserSessionSBean userSession = getUserSession(request);
		  userSession.refresh(usermanager.unFollow(userSession.getPortalid(),userSession.getUser().getId(),((UserActionForm)form).getUserid()));
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("unFollowSuccess");
	}
	public ActionForward requestFriendship(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			User friend = usermanager.getUser(userSession.getPortalid(),((UserActionForm)form).getUserid());
			String[] values = new String[2];
			values[0] = ""+userSession.getUser().getId();
		  values[1] = ""+friend.getId();
			request.setAttribute("signature",UserManagerBean.getMessageDigest(values));
		  String html = getServletContextUtils().getResourceAsString(userSession.getUser(),request,response,"/user/friendshipRequestMail.jsp");
		  InternetAddress portalEmail = portalmanager.getEmail(userSession.getPortalid());
			String subject = "Friendship request from "+userSession.getUser().getUserid();
			try
			{
			  subject = resourceBundle.getString("friendShipRequestFromUserUSER");
				subject.replaceAll("{0}",userSession.getUser().getUserid());
			} catch (MissingResourceException e2)
			{
				log.warn(e2.getMessage());
			}
			getMailRelay().send(portalEmail.getAddress(), friend.getEmail(), subject , null, html);
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("requestFriendshipSuccess");
	}
	public ActionForward acceptFriendship(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			userSession.refresh(usermanager.acceptFriendship(userSession.getPortalid(),userSession.getUser().getId(),((UserActionForm)form).getUserid(),request.getParameter("signature")));
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("acceptFriendshipSuccess");
	}
	public ActionForward destroyFriendship(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			userSession.refresh(usermanager.destroyFriendship(userSession.getPortalid(),userSession.getUser().getId(),((UserActionForm)form).getUserid()));
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("destroyFriendshipSuccess");
	}

}
